/**
 * 消息提示系统工具模块
 * 提供全局消息通知功能，支持不同类型的消息展示
 */
import { createApp, h } from 'vue'
import type { VNode } from 'vue'
import MessageToast from '../components/common/MessageToast.vue'

// 消息实例接口
export interface MessageInstance {
  id: string
  vnode: VNode
  vm: any
  close: () => void
}

// 消息配置接口
export interface MessageOptions {
  message: string
  type?: 'success' | 'warning' | 'error' | 'info'
  duration?: number
  showClose?: boolean
  customStyle?: Record<string, string>
  onClose?: () => void
}

// 消息队列
const instances: MessageInstance[] = []
// 消息ID计数器
let seed = 1

// 创建唯一ID
const getInstanceID = (): string => {
  const id = `message_${seed}`
  seed++
  return id
}

// 获取消息容器
const getContainer = (): HTMLElement => {
  let container = document.getElementById('message-container')
  if (!container) {
    container = document.createElement('div')
    container.id = 'message-container'
    document.body.appendChild(container)
  }
  return container
}

// 关闭单个消息
const closeMessage = (id: string, userInitiated: boolean = false): void => {
  const index = instances.findIndex(instance => instance.id === id)
  if (index === -1) return

  const instance = instances[index]
  // 添加额外的空值检查，确保instance存在
  if (!instance) return
  
  // 调用组件的关闭方法，确保vm存在
  if (instance.vm && typeof instance.vm.hide === 'function') {
    instance.vm.hide()
  }
  // 从实例数组中移除
  instances.splice(index, 1)
  
  // 如果不是用户主动关闭（比如自动关闭），不需要触发onClose
  if (userInitiated && instance.vm && instance.vm.props && typeof instance.vm.props.onClose === 'function') {
    instance.vm.props.onClose()
  }
}

// 创建消息实例
const createInstance = (options: MessageOptions): MessageInstance => {
  const id = getInstanceID()
  const container = getContainer()
  
  // 确保container存在
  if (!container) {
    console.error('Failed to create message container')
    // 返回一个空的实例对象，避免后续操作出错
    const emptyInstance: MessageInstance = {
      id,
      vnode: {} as VNode,
      vm: {},
      close: () => {}
    }
    return emptyInstance
  }
  
  try {
    // 创建应用实例
    const app = createApp({
      render() {
        return h(MessageToast, {
          ...options,
          onClose: () => {
            // 清理应用实例
            setTimeout(() => {
              try {
                app.unmount()
                const element = document.getElementById(id)
                if (element && element.parentNode) {
                  element.parentNode.removeChild(element)
                }
              } catch (error) {
                console.error('Error during message cleanup:', error)
              }
            }, 300)
          }
        })
      }
    })
    
    // 创建挂载节点
    const mountNode = document.createElement('div')
    mountNode.id = id
    container.appendChild(mountNode)
    
    // 挂载应用
    const vm = app.mount(mountNode)
    
    // 创建实例对象
    const instance: MessageInstance = {
      id,
      vnode: h(MessageToast, options),
      vm: vm || {},
      close: () => closeMessage(id, true)
    }
    
    // 添加到实例数组
    instances.push(instance)
    
    // 处理队列位置
    updateInstancePositions()
    
    return instance
  } catch (error) {
    console.error('Error creating message instance:', error)
    // 清理可能创建的节点
    const element = document.getElementById(id)
    if (element && element.parentNode) {
      element.parentNode.removeChild(element)
    }
    // 返回一个空的实例对象
    const emptyInstance: MessageInstance = {
      id,
      vnode: {} as VNode,
      vm: {},
      close: () => {}
    }
    return emptyInstance
  }
}

// 更新消息实例位置
const updateInstancePositions = (): void => {
  // 这里可以根据需要实现消息队列的堆叠效果
  // 目前我们的组件设计是居中显示，不需要调整位置
}

// 关闭所有消息
export const closeAll = (): void => {
  const ids = instances.map(instance => instance.id)
  ids.forEach(id => closeMessage(id))
}

// 主函数式API
export const showMessage = (options: MessageOptions | string): MessageInstance => {
  try {
    // 处理字符串参数
    if (typeof options === 'string') {
      options = { message: options }
    }
    
    // 验证必要的参数
    if (!options || !options.message) {
      console.error('Message content is required')
      // 返回空实例对象避免错误
      const emptyInstance: MessageInstance = {
        id: 'invalid_message',
        vnode: {} as VNode,
        vm: {},
        close: () => {}
      }
      return emptyInstance
    }
    
    // 创建实例
    return createInstance(options)
  } catch (error) {
    console.error('Error showing message:', error)
    // 返回空实例对象避免错误
    const emptyInstance: MessageInstance = {
      id: 'error_message',
      vnode: {} as VNode,
      vm: {},
      close: () => {}
    }
    return emptyInstance
  }
}

// 为每种类型创建快捷方法
export const successMessage = (message: string | MessageOptions): MessageInstance => {
  const options: MessageOptions = typeof message === 'string' 
    ? { message, type: 'success' as const } 
    : { ...message, type: 'success' as const }
  return showMessage(options)
}

export const warningMessage = (message: string | MessageOptions): MessageInstance => {
  const options: MessageOptions = typeof message === 'string' 
    ? { message, type: 'warning' as const } 
    : { ...message, type: 'warning' as const }
  return showMessage(options)
}

export const errorMessage = (message: string | MessageOptions): MessageInstance => {
  const options: MessageOptions = typeof message === 'string' 
    ? { message, type: 'error' as const } 
    : { ...message, type: 'error' as const }
  return showMessage(options)
}

export const infoMessage = (message: string | MessageOptions): MessageInstance => {
  const options: MessageOptions = typeof message === 'string' 
    ? { message, type: 'info' as const } 
    : { ...message, type: 'info' as const }
  return showMessage(options)
}

// 创建Vue插件对象
export const MessagePlugin = {
  install: (app: any) => {
    // 添加全局属性
    app.config.globalProperties.$message = {
      show: showMessage,
      success: successMessage,
      warning: warningMessage,
      error: errorMessage,
      info: infoMessage,
      closeAll
    }
    
    // 添加到app实例上，便于组合式API使用
    app.provide('message', {
      show: showMessage,
      success: successMessage,
      warning: warningMessage,
      error: errorMessage,
      info: infoMessage,
      closeAll
    })
  }
}

// 导出默认对象，包含所有方法
export default {
  show: showMessage,
  success: successMessage,
  warning: warningMessage,
  error: errorMessage,
  info: infoMessage,
  closeAll,
  install: MessagePlugin.install
}